package com.jintu.portal.service.datadriver.parser.impl;

import com.alibaba.fastjson.JSONObject;
import com.jintu.portal.service.datadriver.repository.SourceDataMongoDao;
import com.jintu.portal.config.Constant;
import com.jintu.portal.pojo.submit.DataResponse;
import com.jintu.portal.service.datadriver.parser.DataParser;
import com.jintu.portal.service.datadriver.parser.ParserCommon;
import com.jintu.portal.service.datadriver.pojo.MsgRespCode;
import com.jintu.portal.service.datadriver.pojo.RespInfo;
import com.jintu.portal.service.datadriver.pojo.Response;
import com.jintu.portal.service.datadriver.pojo.SysRespCode;
import com.jintu.portal.service.datadriver.pojo.entity.SourceData;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.bson.Document;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author very
 */
@Slf4j
@Component
public class IdCardAndMobileCheckParser implements DataParser {

    @Resource(name = "sourceDataMongoDao")
    private SourceDataMongoDao sourceDataMongoDao;

    @Override
    public boolean parseAndSaveData(String data, DataResponse dataResponse, Integer userId) {
        if (StringUtils.isBlank(data)) {
            return ParserCommon.isDataSourceIsEmpty(dataResponse);
        }
        Response response = JSONObject.parseObject(data, Response.class);
        String retCode = response.getRetCode();
        if (SysRespCode.QUERY_SUCCESS.getCode().equals(retCode)) {
            RespInfo respInfo = response.getRetInfo();
            ParserCommon.wrapSyncDataSuccess(dataResponse);
            Document savingData = new Document();
            if(MsgRespCode.EQUAL.getCode().equals(respInfo.getCode())){
                savingData.put("isConsistent", Constant.Y);
            } else {
                savingData.put("isConsistent", Constant.N);
            }
            SourceData syncData = ParserCommon.wrapSourceSavingData(dataResponse, userId, savingData);
            sourceDataMongoDao.saveSourceData(syncData, dataResponse.getDataSourceCode());
            return true;
        } else {
            dataResponse.setResponseJson(JSONObject.parseObject(JSONObject.toJSONString(response)));
            return false;
        }
    }
}
